<template>
  <div class="createPay">
    <div>
      <el-button type="primary" size="mini" @click="newlyAdjustment">{{ $t('btn.save') }}</el-button>
    </div>
    <el-tabs v-model="activeName">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form :model="subDetails" label-width="100px" size="mini">
          <el-form-item :label="$t('market.billType')">
            <el-select
              v-model="subDetails.fbillTypeId"
              @change="queryProval"
            >
              <el-option
                v-for="item in billtypes"
                :key="item.fid"
                :label="item.fname"
                :value="item.fid"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.orderDate')">
            <el-date-picker
              v-model.trim="subDetails.fdate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 152px"
            />
          </el-form-item>
          <el-form-item :label="$t('market.endData')">
            <el-date-picker
              v-model.trim="subDetails.fenddate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 152px"
            />
          </el-form-item>
          <el-form-item :label="$t('market.cust')" prop="fcustId">
            <el-autocomplete
              v-model="subDetails.fcustName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch"
              @focus="queryTBdCustomerList"
              @select="clientData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="clientVisiblit = true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.currency2')" prop="fsettlecurrId">
            <el-autocomplete
              v-model="subDetails.fcurrencyName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch5"
              @focus="queryTBdCurrency"
              @select="currencySelectRow"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="openCurrency = true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.saler')" prop="fsalerId">
            <el-autocomplete
              v-model="subDetails.fsalerName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch3"
              @focus="querySalesperson(1)"
              @select="purchaseData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="purchaseVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fuserName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.recCondition')" prop="fpayconditionId">
            <el-autocomplete
              v-model="subDetails.fpayconditionName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch4"
              @focus="querytReccondition"
              @select="gatheringData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="gatheringVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <!--          <el-form-item label="结算组织">-->
          <!--            <el-select v-model.trim="subDetails.orgSet">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="收款组织">-->
          <!--            <el-select v-model.trim="subDetails.orgCol">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="销售组织">-->
          <!--            <el-select v-model.trim="subDetails.orgSal" @change="saleHeadel">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
        </el-form>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.fince')" name="two">
        <el-form :model="subDetails" label-width="100px" size="mini">
          <el-form-item :label="$t('market.exchangeType')">
            <el-input v-model.trim="subDetails.fexchangetype" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.localCurr')">
            <el-input v-model.trim="subDetails.flocalCurr" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.exchangeRate')">
            <el-input v-model.trim="subDetails.fexchangerate" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.notrateamount')">
            <el-input v-model.trim="subDetails.fbillamount" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.billtaxamount')">
            <el-input v-model.trim="subDetails.fbilltaxamount" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.billallamount')">
            <el-input v-model.trim="subDetails.fbillallamount" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.notrateamount_lc')" label-width="120px">
            <el-input v-model.trim="subDetails.fbillamountLc" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.billtaxamount_lc')">
            <el-input v-model.trim="subDetails.fbilltaxamountLc" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.billallamount_lc')" label-width="110px">
            <el-input v-model.trim="subDetails.fbillallamountLc" disabled />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div class="table-content">
      <div style="margin-bottom: 5px;">
        <el-button size="mini" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
        <el-button size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
        <el-button size="mini" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
      </div>
      <jc-table
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        serial
        sortable
        @rowClick="rowClick"
        @cellClick="cellClick"
      >
        <!--    物料编码    -->
        <template v-slot:btnState="col">
          <el-input
            v-model.trim="col.scope.row.fnumber"
            size="mini"
            style="width: 100%"
            @input="getAtuo(col.scope.$index, col.scope.row.fnumber)"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="handleGetMateriel(col.scope.$index)"
            />
          </el-input>
          <div v-if="aotuTab && material === col.scope.$index" :class="material<7 ? 'tabPosit': 'tabPosit1'">
            <number-code :fnumber="fnumber" @material="materialData" />
          </div>
        </template>
        <!--    数量  -->
        <template v-slot:btnSlot="col">
          <el-input-number
            v-model.number="col.scope.row.fcalQty"
            size="mini"
            :min="0"
            @change="handelQty(col.scope.$index)"
          />
        </template>
        <!--    含税单价  -->
        <template v-slot:tagSlot="col">
          <el-input-number
            v-model.number="col.scope.row.ftaxprice"
            :min="0"
            size="mini"
            :precision="4"
            @change="handelQty(col.scope.$index)"
          />
        </template>
        <!--    税率  -->
        <template v-slot:billSlot="col">
          <el-input-number
            v-model.number="col.scope.row.ftaxrate"
            :min="0"
            :max="100"
            size="mini"
            @change="handelQty(col.scope.$index)"
          />
        </template>
        <!--  折扣率  -->
        <template v-slot:orderSlot="col">
          <el-input-number
            v-model.number="col.scope.row.fdiscountrate"
            :min="0"
            :max="100"
            size="mini"
            @change="handelQty(col.scope.$index)"
          />
        </template>
        <!--    备注  -->
        <template v-slot:btnStates="col">
          <el-input v-model.number="col.scope.row.fremark" size="mini" />
        </template>
      </jc-table>
    </div>
    <!--币别-->
    <currency v-if="openCurrency" @currency="currencySelectRow" />
    <!--    物料弹窗-->
    <material v-if="openMaterialDialog" @material="materialData" />
    <!--客户列表-->
    <client v-if="clientVisiblit" @client="clientData" />
    <!--采购员-->
    <market v-if="purchaseVisiblit" :staff-type="staffType" @market="purchaseData" />
    <!--收款条件列表-->
    <gathering v-if="gatheringVisiblit" @gathering="gatheringData" />
  </div>
</template>

<script>
import {
  createReceivableBill
} from '@/api/financial/cashier'
import { queryFxxchange, queryOrgDetail, queryRate, queryViewItem } from '@/api/marketManage/marketOrder'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import billFa from '@/views/financial/cashier/mixins'
import bility from '@/mixin/Operability'

export default {
  name: 'CreatePayable',
  components: {
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    material: () => import('@/views/market/marketManage/createMarkerOrder/components/material'),
    client: () => import('@/views/market/marketManage/createMarkerOrder/components/client'),
    market: () => import('@/views/market/marketManage/createMarkerOrder/components/market'),
    gathering: () => import('@/views/market/marketManage/createMarkerOrder/components/gathering'),
    numberCode: () => import('@/components/NumberCode')
  },
  mixins: [autocomplete, billFa, bility],
  data() {
    return {
      aotuTab: false,
      fnumber: '',
      material: 0,
      clientVisiblit: false, // 客户弹窗
      openCurrency: false, // 币别、价目表、价格类型
      openMaterialDialog: false, // 物料弹窗
      purchaseVisiblit: false, // 2-采购员(1-销售员)
      staffType: 1, // 采购员
      gatheringVisiblit: false, // 收款条件
      subDetails: {
        fdocumentstatus: 'A',
        fbillTypeId: 1262,
        fdate: new Date(),
        fenddate: '',
        fcustId: '',
        fsettlecurrId: '',
        fsalerId: '',
        fpayconditionId: '',
        fcurrencyName: '',
        flocalCurr: '',
        fexchangerate: '',
        fexchangetype: '',
        fexchangetypeId: '',
        fbillamount: 0,
        fbillamountLc: 0,
        fbilltaxamount: 0,
        fbilltaxamountLc: 0,
        fbillallamount: 0,
        fbillallamountLc: 0,
        orgSet: 1,
        orgCol: 1,
        orgSal: 1
      },
      activeName: 'first',
      billtypes: [], // 单据类型
      indexSelf: 0,
      // 表头
      tableData: [{
        fmodel: '', fnumber: '', fname: '', funitName: '', fprice: 0, fcalQty: 0,
        ftaxprice: 0, ftaxrate: 0, fremark: '', famount: 0, ftaxamount: 0, fallamount: 0,
        fdiscountrate: 0, fdiscount: 0
      }], // 应付单数据
      tableHeight: '70vh',
      tableHeader: [
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('market.fmaterial'), type: 'state', prop: 'fnumber', width: '150' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', width: '200' },
        { label: this.$t('market.funit'), prop: 'funitName', width: '80' },
        { label: this.$t('market.fprice'), prop: 'fprice', width: '80' },
        { label: this.$t('market.chargeQty'), type: 'btn', prop: 'fcalQty', width: '80' },
        { label: this.$t('market.ftaxPrice'), type: 'tag', prop: 'ftaxprice', width: '80' },
        { label: this.$t('market.ftaxRate'), type: 'bill', prop: 'ftaxrate', width: '80' },
        { label: this.$t('market.note'), type: 'states', prop: 'fremark' },
        { label: this.$t('market.notrate'), prop: 'famount', width: '80' },
        { label: this.$t('market.billtaxamount'), prop: 'ftaxamount', width: '80' },
        { label: this.$t('market.billallamount'), prop: 'fallamount', width: '80' },
        { label: this.$t('market.fdiscountRate'), type: 'order', prop: 'fdiscountrate', width: '80' },
        { label: this.$t('market.discount'), prop: 'fdiscount', width: '80' }
      ]
    }
  },
  created() {
    this.queryTBasBilltype()
    this.queryProval()
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    // 监听单据类型
    queryProval() {
      const DATA = {
        fid: this.subDetails.fbillTypeId || 0,
        viewName: 'SX_FRECEIVABLE_BILLTYPE'
      }
      queryFxxchange(DATA).then(res => {
        if (res.code === 0) {
          this.subDetails = {
            ...this.subDetails,
            orgSet: res.data.fsettleorgid,
            orgCol: res.data.fsettleorgid,
            orgSal: res.data.fsaleorgid,
            fcurrencyName: res.data.fsettleCurr, // 币别
            fsettlecurrId: res.data.fsettleCurrId, // 币别id
            fexchangetype: res.data.fexchangeType, // 汇率类型
            fexchangetypeId: res.data.fexchangeTypeId, // 汇率类型id
            fexchangerate: res.data.fexchangeRate, // 汇率
            ...res.data
          }
        }
      })
    },
    // 监听组织
    saleHeadel(forgids) {
      this.subDetails.orgCol = forgids
      this.subDetails.orgSet = forgids
      queryOrgDetail({ forgids }).then(res => {
        if (res.code === 0) {
          this.subDetails = {
            ...this.subDetails,
            orgSet: res.data.fsettleorgid,
            orgCol: res.data.fsettleorgid,
            orgSal: res.data.fsaleorgid,
            fcurrencyName: res.data.fsettleCurr, // 币别
            fsettlecurrId: res.data.fsettleCurrId, // 币别id
            fexchangetype: res.data.fexchangeType, // 汇率类型
            fexchangetypeId: res.data.fexchangeTypeId, // 汇率类型id
            fexchangerate: res.data.fexchangeRate, // 汇率
            ...res.data
          }
        }
      })
    },
    // 保存
    newlyAdjustment() {
      const DATA = {
        ...this.subDetails,
        details: this.tableData
      }
      createReceivableBill(DATA).then(res => {
        if (res.code === 0) {
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: `/receivableDetail/${res.data.fid}` })
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.material = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber = fnumber
      }, 600)
    },

    // 查询汇率
    async querySalerRate() {
      const DATA = {
        tocurrId: this.subDetails.flocalCurrId,
        fromcurrId: this.subDetails.fsettlecurrId,
        queryDate: this.subDetails.fdate
      }
      const { data: RES, code, message } = await queryRate(DATA)
      if (code === 0) {
        this.subDetails.fexchangerate = RES.exchangeRate
        this.subDetails.fexchangetype = RES.exchangeTypeName
        this.subDetails.fexchangetypeId = RES.exchangeTypeId
      } else {
        this.subDetails.fexchangerate = ''
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 查询单据类型
    async queryTBasBilltype() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_FRECEIVABLE_BILLTYPE' })
      this.billtypes = RES.list
    },
    // 监听数量
    handelQty(index) {
      const item = this.tableData[index]
      item.fprice = (item.ftaxprice / (1 + (item.ftaxrate / 100))).toFixed(2)
      item.famount = (item.fprice * item.fcalQty * (1 - (item.fdiscountrate / 100))).toFixed(2)
      item.fallamount = (item.ftaxprice * item.fcalQty * (1 - (item.fdiscountrate / 100))).toFixed(2)
      item.ftaxamount = (item.fallamount - item.famount).toFixed(2)
      item.fdiscount = (item.ftaxprice * item.fcalQty * (item.fdiscountrate / 100)).toFixed(2)
      this.subDetails.fbillamount = 0
      this.subDetails.fbilltaxamount = 0
      this.subDetails.fbillallamount = 0
      this.tableData.forEach(res => {
        this.subDetails.fbillamount += res.famount * 1
        this.subDetails.fbilltaxamount += res.ftaxamount * 1
        this.subDetails.fbillallamount += res.fallamount * 1
      })
      const fexchangerate = this.subDetails.fexchangerate
      this.subDetails.fbillamountLc = (this.subDetails.fbillamount * fexchangerate).toFixed(2)
      this.subDetails.fbilltaxamountLc = (this.subDetails.fbilltaxamount * fexchangerate).toFixed(2)
      this.subDetails.fbillallamountLc = (this.subDetails.fbillallamount * fexchangerate).toFixed(2)
    },
    // 打开物料编码
    handleGetMateriel(index) {
      this.material = index
      this.openMaterialDialog = true
    },
    // 物料选中
    materialData(item) {
      if (item.fmaterialId) {
        const items = this.tableData[this.material]
        items.fmaterialId = item.fmaterialId
        items.fnumber = item.fnumber
        items.fname = item.fname
        items.fdescripTion = item.fdescripTion
        items.funitId = item.fsaleUnitId
        items.funitName = item.fsaleUnit
        items.fmodel = item.fmodel
        this.aotuTab = false
      }
      this.openMaterialDialog = false
    },
    // 币别选中
    currencySelectRow(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.subDetails.fsettlecurrId = item.fsettleCurrId || item.fcurrencyId
        this.subDetails.fcurrencyName = item.fsettleCurrIdName || item.fname
        this.querySalerRate()
      }
      this.openCurrency = false
    },
    // 获取销售员
    purchaseData(ev) {
      if (ev.fuserId) {
        this.subDetails.fsalerName = ev.fuserName
        this.subDetails.fsalerId = ev.fuserId
      }
      this.purchaseVisiblit = false
    },
    // 获取客户数据(子传父)
    clientData(item) {
      if (item.fcustId) {
        this.subDetails.fcustId = item.fcustId
        this.subDetails.fcustName = item.fname
      }
      this.clientVisiblit = false
    },
    // 收款条件列表
    gatheringData(item) {
      if (item.fvalue) {
        this.subDetails.fpayconditionName = item.fname
        this.subDetails.fpayconditionId = item.fid
      }
      this.gatheringVisiblit = false
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增行
    newHang() {
      this.tableData.push({
        fmodel: '', fnumber: '', fname: '', funitName: '', fprice: 0, fcalQty: 0,
        ftaxprice: 0, ftaxrate: 0, fremark: '', famount: 0, ftaxamount: 0, fallamount: 0,
        fdiscountrate: 0, fdiscount: 0
      })
    },
    // 删除行
    delHang() {
      this.tableData.splice(this.indexSelf, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
.tabPosit {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: 3.5vh;
  left: 0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 99999!important;
}
.tabPosit1 {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: -25.69vh;
  left:0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 9999;
}
.createPay {
  @include listBom;
  .header{
    margin-top: 5px;
    .header-name{
      span {
        width: 100px;
        margin-right: 10px;
        text-align: right;
      }
    }
  }
  .el-table{
    &::v-deep .el-input-number .el-input__inner{
      padding: 0;
      width: 75px;
      height: 30px;
    }
    &::v-deep .el-input-number .el-input{
      width: 75px;
      height: 35px;
      line-height: 35px;
    }
    &::v-deep .el-input-number--mini{
      width: 75px;
    }
    &::v-deep .el-input-number__increase{
      display: none;
    }
    &::v-deep .el-input-number__decrease{
      display: none;
    }
    &::v-deep .el-table__footer-wrapper tbody td{
      background: #fdf6ec!important;
    }
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 35px;
      width: 268px;
      margin-bottom: 3px;
      //&::v-deep .el-input--mini .el-input__inner{
      //  height: 22px;
      //}
      .btnType {
        margin-right: 20px;
      }

      .el-date-editor.el-input {
        width: 100% !important;
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
